package xyz.xuminghai.javafx_learn.scene.control;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 2023/1/17 14:37 星期二<br/>
 *
 * @author xuMingHai
 */
public class ComboBoxApp extends Application {

    private final AnchorPane anchorPane = new AnchorPane();

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void init() {
        List<String> list = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
            list.add("str" + i);
        }

        ComboBox<String> comboBox = new ComboBox<>(FXCollections.observableArrayList(list));
        // 设置可见行数
//		comboBox.setVisibleRowCount(20);
        // 设置可编辑文本框
        comboBox.setEditable(true);
        TextField textField = comboBox.getEditor();
        textField.textProperty().addListener((observable, oldValue, newValue) -> {
            // TODO: 选中一个Item，再次修改存在递归问题
            List<String> linkedList = new LinkedList<>();
            list.forEach(s -> {
                if (s.contains(newValue)) {
                    linkedList.add(s);
                }
            });
            comboBox.setItems(FXCollections.observableArrayList(linkedList));
            comboBox.show();
        });
        comboBox.setOnAction(event -> textField.end());

        anchorPane.getChildren().add(comboBox);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle(getClass().getSimpleName());
        primaryStage.setScene(new Scene(anchorPane, 800, 600));
        primaryStage.show();
    }
}
